package com.plugin.core.util;


import java.text.SimpleDateFormat;
import java.util.Date;

public class OrderIdGenUtil {


    private final long workerId;
    private final static long twepoch = 1288834974657L;
    private long sequence = 0L;
    private final static long workerIdBits = 5L;
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final static long sequenceBits = 12L;
    private final static long workerIdShift = sequenceBits;
    private final static long timestampLeftShift = sequenceBits + workerIdBits;
    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    private long lastTimestamp = -1L;



    private static OrderIdGenUtil idGenerator=new OrderIdGenUtil(2);

    public OrderIdGenUtil(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException("worker Id can't be greater than " + maxWorkerId + " or less than 0");
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards.");
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;
        return ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }


    /**
     * 获取支付订单编号
     * @return
     */
    public static String getPayOrderNo() {
        return "P_" + getTimestamp()+"_"+String.valueOf(idGenerator.nextId()).substring(7);
    }

    /**
     * 获取退款订单编号
     * @return
     */
    public static String getRefundOrderNo() {
        return "R_" + getTimestamp()+"_"+String.valueOf(idGenerator.nextId()).substring(7);
    }

    /**
     * 获取充值订单编号
     * @return
     */
    public static String getChargeOrderNo() {
        return "C_" + getTimestamp()+"_"+String.valueOf(idGenerator.nextId()).substring(7);
    }

    /**
     * 获取订单服务编号
     * @return
     */
    public static String getTradeOrderNo() {
        return "X_" + getTimestamp()+"_"+String.valueOf(idGenerator.nextId()).substring(7);
    }
    /**
     * 获取编号
     * @return
     */
    public static String getTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        return newDate;
    }

}